package com.yonyou.brigade.third_parties.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yonyou.brigade.third_parties.common.dao.BriIconTenantMapper;
import com.yonyou.brigade.third_parties.common.model.BriIconTenant;
import com.yonyou.brigade.third_parties.common.model.BriIconTenantDTO;
import com.yonyou.brigade.third_parties.common.service.IBriIconTenantService;
import com.yonyou.brigade.util.HttpClientUtil;
import com.yonyou.ybzboot.starter.common.exception.CustomException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author houyb
 * @since 2020-04-22
 */
@Service
public class BriIconTenantServiceImpl extends ServiceImpl<BriIconTenantMapper, BriIconTenant> implements IBriIconTenantService {

    private static final Logger logger = LoggerFactory.getLogger(BriIconTenantServiceImpl.class);

    @Value("${ybz.openApphomeModule.url}")
    private String openApphomeModuleUrl;

    @Value("${ybz.baseUrl}")
    private String ybzBaseUrl;

    @Autowired
    private BriIconTenantMapper briIconTenantMapper;

    @Override
    public JSONObject updateIconStatus(JSONObject param) {
        JSONObject rs = new JSONObject();
        logger.info("更新图片勾选状态：" + param.toJSONString());
        String tenant = param.getString("tenantId");
        String userid = param.getString("userId");
        String url = ybzBaseUrl + openApphomeModuleUrl + "?tenantId=" + tenant;
        JSONArray iconArr = param.getJSONArray("icon");
        List<BriIconTenant> iconList = new ArrayList<>();
        JSONObject rqYbzParam = new JSONObject();
        rqYbzParam.put("type","third");
        rqYbzParam.put("tenant", tenant);
        rqYbzParam.put("userId", userid);
        JSONArray dataArr = new JSONArray();
        for (int i = 0; i < iconArr.size(); i++) {
            JSONObject icon = iconArr.getJSONObject(i);
            String iconKey = icon.getString("iconKey");
            Integer checked = icon.getInteger("checked");
            //先查询是否有关联关系
            Wrapper<BriIconTenant> wrapper = new EntityWrapper<>();
            wrapper.eq("tenant", tenant);
            wrapper.eq("icon_key", iconKey);
            BriIconTenant briIconTenant = this.selectOne(wrapper);
            if (briIconTenant == null){
                briIconTenant = getBriIconTenant(tenant, icon);
            }
            briIconTenant.setChecked(checked);
            iconList.add(briIconTenant);

            //拼装友报账请求参数
            JSONObject data = new JSONObject();
            data.put("key", iconKey);
            if (checked == null) {
                checked = 0;
            }
            Boolean openingStatus = checked == 1 ? true : false;
            data.put("openingStatus", openingStatus);
            dataArr.add(data);

        }
        rqYbzParam.put("date", dataArr);

        logger.info("请求友报账更新图片状态: " +rqYbzParam.toJSONString());
        String result = HttpClientUtil.doPostJson(url, rqYbzParam.toJSONString());
        logger.info("请求友报账更新图片状态结果: " + result);

        JSONObject respJson = null;
        try {
            respJson = JSON.parseObject(result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("请求友报账更新图片状态异常");
            throw new CustomException(result);
        }
        //如果报账更新成功，则修改商旅
        if (respJson.getString("code") != null && "0".equals(respJson.getString("code"))){
            boolean bool = this.insertOrUpdateBatch(iconList);
            rs.put("success", bool);
            return rs;
        }
        rs.put("success", false);
        return rs;
    }

    @Override
    public List<BriIconTenantDTO> getIconsByChannelCode(String channelCode, String tenantId) {
        return briIconTenantMapper.getIconsByChannelCode(channelCode, tenantId);
    }


    private BriIconTenant getBriIconTenant(String tenant, JSONObject icon) {
        BriIconTenant briIconTenant = new BriIconTenant();
        briIconTenant.setChecked(icon.getInteger("checked"));
        briIconTenant.setIconKey(icon.getString("iconKey"));
        briIconTenant.setTenant(tenant);
        return briIconTenant;
    }
}
